package com.dyz.config;

import com.dyz.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;


import javax.annotation.Resource;

@Configuration
@EnableAuthorizationServer//开启授权服务器功能
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserDetailsServiceImpl userDetailsService;
    @Resource

    private AuthenticationManager authenticationManager;

//    @Resource
//    private RedisConnectionFactory redisConnectionFactory;
    /**
     * 添加第三方客户端信息
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("coin-client")//客户端id
                .secret(passwordEncoder.encode("coin-secret"))//客户端密钥
                .scopes("all")//授权范围
                .accessTokenValiditySeconds(3600)//token有效期
                .authorizedGrantTypes("password","refresh_token")
                .refreshTokenValiditySeconds(6*3600)//refresh-token有效期
                //添加第三方客户端信息,用于内部认证
                .and()
                .withClient("inside-app")
                .secret(passwordEncoder.encode("inside-app-secret"))
                .authorizedGrantTypes("client_credentials")
                .scopes("all")
                .accessTokenValiditySeconds(3600)
                ;
    }
    /**
     * 配置验证管理器 UserDetailsService
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)//添加验证管理器
                 .userDetailsService(userDetailsService)//添加用户信息
        .tokenStore(jwtTokenStore())//添加token存储器(也就是将生成的token保存到jwt中进行共享)
        .tokenEnhancer(jwtAccessTokenConverter());//添加token增强器(jwt)
    }

    /**
     * 创建一个jwtTokenStore
     * @return
     */
    private  TokenStore jwtTokenStore() {
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore;
    }

    /**
     * 创建一个jwtAccessTokenConverter
     * @return
     */
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 确保coinexchange.jks文件位于src/main/resources目录下
        ClassPathResource classPathResource = new ClassPathResource("coinexchange.jks");
        if (!classPathResource.exists()) {
            throw new RuntimeException("密钥库文件coinexchange.jks不存在，请检查文件路径和权限！");
        }
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "coinexchange".toCharArray());
        jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("coinexchange", "coinexchange".toCharArray()));
        return jwtAccessTokenConverter;
    }
//    /**
//     * 创建一个redisTokenStore
//     * @return
//     */
//    public TokenStore redisTokenStore(){
//        return new RedisTokenStore(redisConnectionFactory);
//    }
}
